<script setup lang="ts">
import {
  ProductPageVO,
  ProductPageQuery,
  ProductSaveOrUpdateVO,
} from "@/api/product/types";
import {
  batchDelete,
  deleteProduct,
  getProductDetail,
  getProductPage,
  updateStatus,
} from "@/api/product";
import router from "@/router";
import { getCategoryTree } from "@/api/category";
import { convertProductCateOptions } from "@/utils/convertCategoryTree";
const listLoading = ref(false);
const productList = ref<ProductPageVO[]>([]);
const queryParams = ref<ProductPageQuery>({
  title: "",
  categoryId: undefined,
  status: undefined,
  pageNum: 1,
  pageSize: 10,
});
const total = ref(0);
const productCateOptions = ref<any>([]);
const queryFormRef = ref(ElForm);
const selectProductCateValue = ref<any>([]);
const ids = ref([]);
const drawerVisible = ref(false);
const defaultParam = {
  id: undefined,
  categoryId: undefined,
  title: "",
  itemType: "",
  image: "",
  price: 0,
  num: 1,
  sellPoint: "",
  priority: 1,
  status: 1,
  thumbnails: [],
  categoryName: "",
};
const productParam = ref<ProductSaveOrUpdateVO>(defaultParam);
/**
 * 数据请求区域
 */
// 分页查询
const handleQuery = () => {
  listLoading.value = true;
  getProductPage(queryParams.value)
    .then((res) => {
      // console.log(res.data.list);
      productList.value = res.data.list;
      total.value = res.data.total;
    })
    .finally(() => {
      listLoading.value = false;
    });
};
// 更新状态
const handleStatusChange = (row: any) => {
  // 弹出框提示是否更新状态
  ElMessageBox.confirm("确定要修改该商品的状态吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      updateStatus(row.id, row.status).then(() => {
        ElMessage({
          type: "success",
          message: "修改成功",
        });
      });
    })
    .catch(() => {
      row.status === 1 ? (row.status = 0) : (row.status = 1);
    });
};
const handleUpdate = (row: any) => {
  router.push({ path: "/product/updateProduct", query: { id: row.id } });
};
// 删除分类
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确定要删除该商品吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteProduct(row.id).then(() => {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
      });
      handleQuery();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};
const handleDetail = (row: any) => {
  getProductDetail(row.id).then((res) => {
    productParam.value = res.data;
    // console.log("详情", productParam.value);
  });
  drawerVisible.value = true;
};
// 获取分类树形数据
const getProductCateOptions = () => {
  // 获取分类树形数据
  getCategoryTree().then((res) => {
    // console.log(res.data);
    productCateOptions.value = convertProductCateOptions(res.data);
  });
};
const handleSelectionChange = (val: any) => {
  ids.value = val.map((item: any) => item.id);
  //console.log(ids.value);
};
// 批量删除商品
const handleBatchDelete = () => {
  // 如果没有选择商品
  if (ids.value.length === 0) {
    ElMessage({
      type: "warning",
      message: "请选择要删除的商品",
    });
    return;
  }
  ElMessageBox.confirm("确定要删除选中的商品吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    batchDelete(ids.value)
      .then(() => {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        handleQuery();
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "已取消删除",
        });
      });
  });
};
const handleAddProduct = () => {
  router.push({ path: "/product/addProduct" });
};
const resetQuery = () => {
  queryFormRef.value.resetFields();
  queryParams.value.pageNum = 1;
  // 清空分类选择
  selectProductCateValue.value = [];
  handleQuery();
};

/**
 * 监听区域
 */
// 监听分类选择
watch(selectProductCateValue, (val) => {
  queryParams.value.categoryId = val[val.length - 1];
  // console.log(queryParams.value.categoryId);
});

handleQuery();
getProductCateOptions();
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        class="form-inline"
      >
        <el-form-item label="商品名称" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="分类名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-cascader
            clearable
            v-model="selectProductCateValue"
            :options="productCateOptions"
          />
        </el-form-item>
        <el-form-item label="上架状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="全部" clearable>
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery"
            ><template #icon><i-ep-search /></template>搜索</el-button
          >
          <el-button @click="resetQuery">
            <template #icon><i-ep-refresh /></template>
            重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never" class="table-container">
      <template #header>
        <el-row>
          <el-col :xs="24" :sm="18" :lg="19">
            <div style="display: flex; align-items: center">
              <el-icon :size="20"><List /></el-icon>
              <span>数据列表</span>
            </div>
          </el-col>
          <el-col :xs="24" :sm="6" :lg="5">
            <div style="display: flex; align-items: center">
              <el-button type="success" @click="handleAddProduct">
                <template #icon><i-ep-plus /></template>
                新增</el-button
              >
              <el-button type="danger" @click="handleBatchDelete">
                <template #icon><i-ep-delete /></template>
                批量删除
              </el-button>
            </div>
          </el-col>
        </el-row>
      </template>
      <el-table
        v-loading="listLoading"
        highlight-current-row
        :data="productList"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="编号" align="center" width="100" />
        <el-table-column label="商品图片" width="120" align="center">
          <template #default="scope"
            ><el-image style="height: 80px" :src="scope.row.image"
          /></template>
        </el-table-column>
        <el-table-column
          prop="title"
          label="商品名称"
          align="center"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          label="商品分类"
          align="center"
          width="100"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-tag type="warning">{{ scope.row.categoryName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否上架" align="center" width="100">
          <template #default="scope">
            <el-switch
              inline-prompt
              :active-value="1"
              :inactive-value="0"
              active-text="是"
              inactive-text="否"
              v-model="scope.row.status"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="商品系列"
          align="center"
          width="120"
          show-overflow-tooltip
        >
          <template #default="scope">
            <span>{{ scope.row.itemType }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="sellPoint"
          label="商品卖点"
          align="center"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column label="价格" align="center" width="80">
          <template #default="scope">
            <span>￥{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column label="库存" align="center" width="100" prop="num" />
        <el-table-column
          label="排序"
          align="center"
          width="80"
          prop="priority"
        />
        <el-table-column
          label="创建人"
          align="center"
          width="100"
          prop="createdUser"
          show-overflow-tooltip
        />
        <el-table-column
          label="创建时间"
          align="center"
          width="120"
          prop="createdTime"
          show-overflow-tooltip
        />
        <el-table-column
          label="修改人"
          align="center"
          width="100"
          prop="modifiedUser"
          show-overflow-tooltip
        />
        <el-table-column
          label="修改时间"
          align="center"
          width="120"
          prop="modifiedTime"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" align="center" label="操作" width="200">
          <template #default="scope">
            <el-button
              type="success"
              size="small"
              @click="handleDetail(scope.row)"
              >详情</el-button
            >
            <el-button
              type="primary"
              size="small"
              @click="handleUpdate(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>
    <el-drawer v-model="drawerVisible" size="50%">
      <el-descriptions class="margin-top" title="商品详情" :column="2" border>
        <el-descriptions-item width="40px">
          <template #label>
            <div class="cell-item">商品编号</div>
          </template>
          {{ productParam.id }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">商品名称</div>
          </template>
          {{ productParam.title }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">商品分类</div>
          </template>
          <el-tag size="small">{{ productParam.categoryName }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item width="40px">
          <template #label>
            <div class="cell-item">商品系列</div>
          </template>
          {{ productParam.itemType }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">商品卖点</div>
          </template>
          {{ productParam.sellPoint }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">商品价格</div>
          </template>
          ¥ {{ productParam.price }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">商品库存</div>
          </template>
          {{ productParam.num }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">商品排序</div>
          </template>
          {{ productParam.priority }}
        </el-descriptions-item>
      </el-descriptions>
      <el-carousel
        style="margin-top: 20px"
        :interval="4000"
        height="300px"
        type="card"
      >
        <el-carousel-item
          v-for="(item, index) in productParam.thumbnails"
          :key="index"
        >
          <!--el-image
            :src="item"
            width="100%"
            height="100%"
            style="object-fit: scale-down"
          /-->
          <img
            :src="item"
            style=" width: 100%; height: 100%;object-fit: scale-down"
            alt="加载失败"
          />
        </el-carousel-item>
      </el-carousel>
    </el-drawer>
  </div>
</template>

<style lang="scss">
.form-inline .el-input {
  --el-input-width: 220px;
}

.form-inline .el-select {
  --el-select-width: 120px;
}

.el-descriptions {
  margin-top: 20px;
}

.cell-item {
  display: flex;
  align-items: center;
}

.margin-top {
  margin-top: 20px;
}

.el-carousel {
  background-color: #c8e2f5; /* 设置背景颜色为灰色 */
}

.el-carousel__item h3 {
  margin: 0;
  line-height: 300px;
  color: #475669;
  text-align: center;
  opacity: 0.75;
}
</style>
